<template>
  <div style="margin-top: 10px;position: relative;" id="loanRecord">
    <div style="margin-right: 240px">
      <el-collapse v-model="callapse">
        <el-collapse-item v-for="item in callapseList" :key="item.id" style="margin-bottom: 15px;"
                          :name="item.id">
          <template slot="title">
            <div class="collapse_title">
              {{ item.name }}
            </div>
          </template>
          <div :id="item.webUrl">
            <div class="collapse_content">
              <component :is="item.webUrl" :routesQuery="routesQuery" :childPermiss="item.children"></component>
            </div>
          </div>
        </el-collapse-item>
      </el-collapse>
    </div>
    <div class="button_list">
      <el-row :gutter="24" style="margin: 0;padding: 0 10px">
        <el-col v-show="permiss[988] || permiss[311]" :span="24" style="margin-bottom: 15px;padding: 0 25px">
          <el-button style="width: 100%" type="primary"
                     @click="clickRows('remind')">{{ $t('新增提醒记录') }}
          </el-button>
        </el-col>
        <el-col v-show="permiss[388]" :span="24" style="margin-bottom: 15px;padding: 0 25px">
          <el-button style="width: 100%" type="primary" @click="clickRows('report')">
            {{ $t('加入黑名单') }}
          </el-button>
        </el-col>
        <el-col v-show="permiss[387] || permiss[986]" :span="24" style="margin-bottom: 15px;padding: 0 25px">
          <el-button style="width: 100%" type="primary" @click="clickRows('collection')">
            {{ $t('新增催收记录') }}
          </el-button>
        </el-col>
      </el-row>
    </div>
    <!--    新增催收记录-->
    <Dialog :title="$t('新增催收记录')" :visible.sync="visibleAddCollection" @cancel="visibleAddCollection = false"
            @confirm="addCollectionConfirm" @close="clearForm('collectionForm')">
      <el-form label-width="120px" ref="collectionForm" :model="collectionForm">
        <el-form-item :label="$t('联系方式')" prop="contactMode" :rules="[
                {required: true, message: this.$t('不能为空'),trigger:'change'}
          ]">
          <el-select v-model="collectionForm.contactMode">
            <el-option :value="0" :label="$t('手机号')"></el-option>
            <el-option :value="1" label="zalo"></el-option>
            <el-option :value="2" label="whatsApp"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="contactModeObj[collectionForm.contactMode]" prop="phone" :rules="[
                {required: true, message: this.$t('不能为空')}
          ]">
          <el-input v-model="collectionForm.phone" oninput="value = value.replace(/[^\d]/g, '')" maxlength="20"></el-input>
        </el-form-item>
        <el-form-item :label="$t('与借款人关系')" prop="contactObject" :rules="[
                {required: true, message: this.$t('不能为空')}
          ]">
          <el-select style="width: 100%" v-model="collectionForm.contactObject">
            <el-option v-for="item in relationList" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('结果')" prop="contactResult" :rules="[
                {required: true, message: this.$t('不能为空')}
          ]">
          <el-select style="width: 100%" @change="collectionChange" v-model="collectionForm.contactResult">
            <el-option v-for="item in contactList" :key="item.key" :label="item.value"
                       :value="item.key"></el-option>
          </el-select>
          <div style="margin-top: 10px">
            <el-tag v-for="item in tagsList" :disable-transitions="true" :effect="item.key === collectionForm.labelList ? 'dark' : 'plain'"
                    :key="item.key"
                    @click="collectionClick(item)" :label="item.key" style="margin: 0 10px 10px 0;cursor: pointer">
              {{ item.value }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item :label="$t('承诺还款时间')" prop="admitTime" v-if="collectionForm.isTime === 1" :rules=" [{ required: true, message: $t(
          '不能为空'),trigger:'blur'}]">
          <el-date-picker
              style="width: 100%"
              :pickerOptions="{
                  disabledDate(time) {
                      //  当日意向客户只能选当天时间 非当日禁用之前时间
                     return collectionForm.labelList === 1 ? time.getTime() !==  new Date(new Date().toLocaleDateString()).getTime() : time.getTime() < Date.now()
                 },
                }"
              v-model="collectionForm.admitTime"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('选择日期')"
              value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('是否申请减免')" prop="isApply" v-if="permiss[1008] || permiss[1010]">
          <el-radio-group v-model="collectionForm.isApply">
            <el-radio :label="1">{{ $t('是') }}</el-radio>
            <el-radio :label="0">{{ $t('否') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--        减免展示减免原因-->
        <template v-if="collectionForm.isApply === 1">
          <el-form-item :label="$t('减免类型')" prop="cause1" :rules="[
          {required: true, message: this.$t('不能为空'),},
        ]">
            <el-select v-model="collectionForm.cause1" @change="collectionChangeType">
              <el-option v-for="item in remissionTypeList" :label="item.value" :value="item.key"
                         :key="item.key"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('减免原因')" prop="cause2" v-if="collectionForm.remissionRequiredRemark !== 1"
                        :rules="[{ required: true, message: $t('不能为空'),trigger:'blur'}]">
            <el-select v-model="collectionForm.cause2">
              <el-option v-for="item in remissionCauseList" :label="item.value" :value="item.key"
                         :key="item.key"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('减免金额')" prop="remissionAmount"
                        :rules="[{ required: true, message: $t('不能为空'),trigger:'blur'}]">
            <el-input v-model="collectionForm.remissionAmount"
                      oninput="value = value.replace(/[^\d.]/g, '')"></el-input>
          </el-form-item>
          <el-form-item :label="$t('上传凭证')">
            <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                ref="upload"
                action="#"
                accept=".jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG"
                :http-request="collectionUpload">
              <img v-if="collectionForm.certificate" :src="collectionForm.certificate" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </template>
        <el-form-item :label="$t('备注')" prop="remarks"
                      :required="collectionForm.remissionRequiredRemark === 1 || collectionForm.isRequiredRemark === 1"
                      :rules="collectionForm.remissionRequiredRemark=== 1 || collectionForm.isRequiredRemark === 1 ? [{ required: true, message: $t(
          '不能为空'),trigger:'blur'}] : []">
          <el-input type="textarea" maxlength="500" show-word-limit v-model="collectionForm.remarks" :rows="4"/>
        </el-form-item>
      </el-form>

    </Dialog>
    <!--    上报黑名单-->
    <Dialog :title="$t('上报黑名单')" :visible.sync="visibleAddBlack" @cancel="visibleAddBlack = false"
            @confirm="submitBlack" @close="clearForm('report')">
      <el-form label-width="120px" :model="report" ref="report">
        <el-form-item prop="cause" :label="$t('原因')"
                      :rules="[ { required: true, message: $t('不能为空'),trigger:'change'} ]">
          <el-select v-model="report.cause" @change="selectReportCause">
            <el-option v-for="item in reportSelectList" :key="item.key" :value="item.key"
                       :label="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('上报黑名单原因')" :required="report.isRemarks === 1 "
                      :rules="report.isRemarks=== 1 ? [{ required: true, message: $t(
          '不能为空'),trigger:'blur'}] : []" prop="blackValue">
          <el-input type="textarea" :rows="5" v-model="report.blackValue"/>
        </el-form-item>
      </el-form>
    </Dialog>
    <!--    新增提醒记录-->
    <Dialog :title="$t('新增提醒记录')" :visible.sync="visibleAddRemind" @cancel="visibleAddRemind = false"
            @confirm="remindSubmit" @close="clearForm('remindForm')">
      <el-form ref="remindForm" :model="remindForm" label-width="120px">
        <el-form-item :label="$t('联系方式')" prop="contactMode" :rules="[
                {required: true, message: this.$t('不能为空'),trigger:'change'}
          ]">
          <el-select v-model="remindForm.contactMode">
            <el-option :value="0" :label="$t('手机号')"></el-option>
            <el-option :value="1" label="zalo"></el-option>
            <el-option :value="2" label="whatsApp"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="contactModeObj[remindForm.contactMode]" prop="phone" :rules="[
                {required: true, message: this.$t('不能为空')}
          ]">
          <el-input v-model="remindForm.phone" oninput="value = value.replace(/[^\d]/g, '')" maxlength="20">
          </el-input>
        </el-form-item>
        <el-form-item :label="$t('与借款人关系')" prop="contactObject" :rules="[
                {required: true, message: this.$t('不能为空')}
          ]">
          <el-select style="width: 100%" v-model="remindForm.contactObject">
            <el-option v-for="item in relationList" :key="item.value" :label="item.label"
                       :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('联系结果')" prop="resultType" :rules="[
                {required: true, message: this.$t('不能为空')}
          ]">
          <el-select style="width: 100%" v-model="remindForm.resultType" @change="remindChange">
            <el-option v-for="item in contactList" :key="item.key" :label="item.value"
                       :value="item.key"></el-option>
          </el-select>
          <div style="margin-top: 10px">
            <el-tag v-for="item in tagsList" :disable-transitions="true" :effect="item.key === remindForm.labelList ? 'dark' : 'plain'"
                    :key="item.key"
                    @click="remindClick(item)" :label="item.key" style="margin: 0 10px 10px 0;cursor: pointer">
              {{ item.value }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item :label="$t('承诺还款时间')" v-if="remindForm.isTime === 1" :rules=" [{ required: true, message: $t(
          '不能为空'),trigger:'blur'}]" prop="admitTime">
          <el-date-picker
              style="width: 100%"
              v-model="remindForm.admitTime"
              type="datetime"
              :pickerOptions="{
                  disabledDate(time) {
                      //  当日意向客户只能选当天时间 非当日禁用之前时间
                 return remindForm.labelList === 1 ? time.getTime() !==  new Date(new Date().toLocaleDateString()).getTime() : time.getTime()< Date.now()
                 },
                }"
              format="yyyy-MM-dd HH:mm:ss"
              :placeholder="$t('选择日期')"
              value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
        <el-form-item :label="$t('是否申请减免')" prop="isApply" v-if="permiss[1014] || permiss[1012]">
          <el-radio-group v-model="remindForm.isApply">
            <el-radio :label="1">{{ $t('是') }}</el-radio>
            <el-radio :label="0">{{ $t('否') }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--        减免展示减免原因-->
        <template v-if="remindForm.isApply === 1">
          <el-form-item :label="$t('减免类型')" prop="cause1" :rules="[
          {required: true, message: this.$t('不能为空'),},
        ]">
            <el-select v-model="remindForm.cause1" @change="remindChangeType">
              <el-option v-for="item in remissionTypeList" :label="item.value" :value="item.key"
                         :key="item.key"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('减免原因')" prop="cause2" v-if="remindForm.remissionRequiredRemark !== 1" :rules="[
          {required: true, message: this.$t('不能为空'),},
        ]">
            <el-select v-model="remindForm.cause2">
              <el-option v-for="item in remissionCauseList" :label="item.value" :value="item.key"
                         :key="item.key"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item :label="$t('减免金额')" prop="remissionAmount" :rules="[{ required: true, message: $t(
          '不能为空'),trigger:'blur'}]">
            <el-input v-model="remindForm.remissionAmount" oninput="value = value.replace(/[^\d.]/g, '')"></el-input>
          </el-form-item>
          <el-form-item :label="$t('上传凭证')">
            <el-upload
                class="avatar-uploader"
                :show-file-list="false"
                ref="upload"
                action="#"
                accept=".jpg,.jpeg,.png,.gif,.bmp,.JPG,.JPEG"
                :http-request="remindUpload">
              <img v-if="remindForm.certificate" :src="remindForm.certificate" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </template>

        <el-form-item :label="$t('备注')" prop="remarks"
                      :required="remindForm.remissionRequiredRemark === 1 || remindForm.isRequiredRemark === 1"
                      :rules="remindForm.remissionRequiredRemark=== 1 || remindForm.isRequiredRemark === 1 ? [{ required: true, message: $t(
          '不能为空'),trigger:'blur'}] : []">
          <el-input type="textarea" maxlength="500" show-word-limit v-model="remindForm.remarks" :rows="4"/>
        </el-form-item>
      </el-form>
    </Dialog>
  </div>
</template>

<script>
// 催收纪录
import CollectionRecord from "./component/loanPanel/collectionRecord";
// 提醒记录
import RemindRecord from "./component/loanPanel/remindRecord";
// 虚拟卡记录
import VirtualCardRecord from "./component/loanPanel/virtualCardRecord";
// 待还明细
import PayBackDetails from "./component/loanPanel/payBackDetails";
// 打款明细
import PaymentDetails from "./component/loanPanel/paymentDetails";
//还款明细
import RepaymenutDetails from "./component/loanPanel/repaymenutDetails";
// 访问记录
import AccessRecord from "./component/loanPanel/accessRecord";
import eventBus from "@/utils/eventBus";
import {reasonTagsList} from "@/utils/tools";
// 抽离js逻辑
import common from "./component/loanPanel/common";
import {selectBlacklistCause} from '@/api/order'
import {addBlackList, addCollectionResultRecord, addTodayExpireResult} from '@/api/postLoan'

export default {
  props: ['panePermiss','routesQuery'],
  data() {
    const {
      collectionList,
    } = reasonTagsList()
    return {
      callapse: [],
      callapseList: [],
      tabs_top: 0,
      visibleAddCollection: false,
      visibleAddBlack: false,
      visibleAddRemind: false,
      collectionForm: {
        contactObject: 1,
        contactMode: 0,
        isApply: 0
      },
      relationList: [
        {label: this.$t('本人'), value: 1},
        {label: this.$t('配偶'), value: 8},
        {label: this.$t('父亲'), value: 2},
        {label: this.$t('母亲'), value: 3},
        {label: this.$t('兄弟'), value: 4},
        {label: this.$t('姐妹'), value: 5},
        {label: this.$t('同事'), value: 6},
        {label: this.$t('朋友'), value: 7},
      ],
      contactList: collectionList,
      tagsList: [],
      report: {
        blackValue: '',
        cause: null,
        isRemarks: null,
      },
      reportSelectList: [],
      remindForm: {
        contactObject: 1,
        isApply: 0,
        contactMode: 0
      },
      permiss: {},
      contactModeObj: {
        0: this.$t('手机号'),
        1: 'zalo',
        2: 'whatsApp',
      }
    }
  },
  mixins: [common],
  components: {
    RemindRecord,
    RepaymenutDetails,
    PaymentDetails,
    PayBackDetails,
    VirtualCardRecord,
    CollectionRecord,
    AccessRecord

  },
  computed: {
    components() {
      return {
        'RemindRecord': 'RemindRecord',
        'RepaymenutDetails': 'RepaymenutDetails',
        'PaymentDetails': 'PaymentDetails',
        'PayBackDetails': 'PayBackDetails',
        'VirtualCardRecord': 'VirtualCardRecord',
        'CollectionRecord': 'CollectionRecord',
        'AccessRecord': 'AccessRecord'
      }
    },
  },
  created() {
    this.getList()
  },
  methods: {
    async getList() {
      const callapseItem = []
      const obj = {}
      const filterAuth = (list) => {
        list.forEach(item => {
          if (item.children && item.children.length) {
            filterAuth(item.children)
          }
          // weburl匹配前端路径
          if (this.components[item.webUrl]) {
            callapseItem.push(item.id)
          } else {
            // 按钮显示隐藏
            obj[item.id] = item.url
          }
          return item
        })
      }
      filterAuth(this.panePermiss)
      this.permiss = obj
      this.callapse = callapseItem
      this.callapseList = this.panePermiss.filter(item => item.webUrl)
      this.$nextTick(() => {
        this.tabs_top = document.getElementById('loanRecord').getBoundingClientRect().top
      })
    },
    async clickRows(type) {
      if (type === 'collection') {
        //  新增催收记录
        this.visibleAddCollection = true
      } else if (type === 'report') {
        //加入黑名单
        this.visibleAddBlack = true
        const res = await selectBlacklistCause()
        if (res.code === 1) {
          this.reportSelectList = res.data
        }
      } else if (type === 'remind') {
        // 添加提醒记录
        this.visibleAddRemind = true
      }
      this.getRemissionCause()
    },
    selectReportCause(value) {
      if (value === 'OTHER') {
        this.report.isRemarks = 1
      } else {
        this.report.isRemarks = 0
      }
    },
    // 添加催收记录
    addCollectionConfirm() {
      this.$refs.collectionForm.validate(async v => {
        if (v) {
          const {orderId, collectionId} = this.routesQuery
          const res = await addCollectionResultRecord({
            loanRecordId: orderId,
            collectionId: collectionId ? parseInt(collectionId) : null,
            ...this.collectionForm
          })
          if (res.code === 1) {
            this.visibleAddCollection = false
            this.$message.success(this.$t('新增成功'))
            eventBus.$emit('addCollectionResultRecord')
          }
        }
      })
    },
    // 催收结果下拉
    collectionChange(value) {
      const {collectionTagsList, collectionList} = reasonTagsList()
      const selectList = collectionTagsList.filter(item => item.pid === value)
      this.tagsList = selectList
      // 默认第一位
      if (selectList.length !== 0) {
        const {key, isTime, isRemarks} = selectList[0]
        this.collectionForm = {
          ...this.collectionForm,
          labelList: key,
          isTime: isTime,
          isRequiredRemark: isRemarks
        }
      } else {
        const selectList = collectionList.filter(item => item.key === value)
        this.collectionForm = {
          ...this.collectionForm,
          labelList: null,
          isRequiredRemark: selectList[0].isRemarks
        }
      }
    },
    // 催收标签点击
    collectionClick({key, isTime, isRemarks}) {
      this.collectionForm = {
        ...this.collectionForm,
        labelList: key,
        isTime: isTime,
        isRequiredRemark: isRemarks
      }
    },
    remindChange(value) {
      const {collectionTagsList, collectionList} = reasonTagsList()
      const selectList = collectionTagsList.filter(item => item.pid === value)
      this.tagsList = selectList
      // 默认第一位
      if (selectList.length !== 0) {
        const {key, isTime, isRemarks} = selectList[0]
        this.remindForm = {
          ...this.remindForm,
          labelList: key,
          isTime: isTime,
          isRequiredRemark: isRemarks
        }
      } else {
        const selectList = collectionList.filter(item => item.key === value)
        this.remindForm = {
          ...this.remindForm,
          labelList: null,
          isRequiredRemark: selectList[0].isRemarks
        }
      }
    },
    remindClick({key, isTime, isRemarks}) {
      this.remindForm = {
        ...this.remindForm,
        labelList: key,
        isTime: isTime,
        isRequiredRemark: isRemarks
      }
    },
    // 上报黑名单
    async submitBlack() {
      this.$refs.report.validate(async v => {
        if (v) {
          const {orderId} = this.routesQuery
          const res = await addBlackList({
            loanRecordId: orderId,
            join: this.report.blackValue,
            cause: this.report.cause
          })
          if (res.code === 1) {
            this.visibleAddBlack = false
            this.$message.success(this.$t('操作成功'))
            eventBus.$emit('addBlack')
          }
        }
      })

    },
    // 添加提醒记录
    remindSubmit() {
      this.$refs.remindForm.validate(async v => {
        if (v) {
          const {orderId} = this.routesQuery
          const res = await addTodayExpireResult({
            loanRecordId: orderId,
            ...this.remindForm,
          })
          if (res.code === 1) {
            this.visibleAddRemind = false
            this.$message.success(this.$t('新增成功'))
            eventBus.$emit('addTodayExpireResult')
          }
        }
      })
    },

    clearForm(type) {
      this.$data[type] = {
        contactObject: 1,
        isApply: 0,
        contactMode: 0
      }
      if (this.$refs.upload) {
        this.$refs.upload.clearFiles()
      }
      this.tagsList = []
      this.$refs[type].resetFields()
    }
  },
}
</script>

<style scoped>
::v-deep .avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

::v-deep .avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.collapse_title {
  margin-left: 15px;
  font-size: 18px;
}

.collapse_content {

  box-sizing: border-box;
}

::v-deep .el-collapse-item__header {
  background-color: #ffedb3 !important;
}

::v-deep .el-collapse-item__content {
  padding-bottom: 0px;
}

.button_list {
  position: absolute;
  width: 240px;
  right: 0;
  top: 0;
}
</style>
